package com.chentf;

import com.chentf.dao.UserDAO;
import com.chentf.struts2.service.UserService;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author chentengfei
 * @desc 工厂模式创建对象
 * @date 2020-12-26 16:20:06
 */
public class BeanFactory {

    public static Properties properties = new Properties();

    //使用静态代码块加载外部配置文件
    static {
        InputStream inputStream = null;
        try {
            //第一步 获得IO输入流
            inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
            //第二步 文件内容 封装 Properties集合中 key = userService value = com.chentf.service.impl.UserServiceImpl
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /*
       对象的创建方式：
          1. 直接调用构造方法 创建对象  UserService userService = new UserServiceImpl();
          2. 通过反射的形式 创建对象 解耦合
              Class clazz = Class.forName("com.baizhiedu.basic.UserServiceImpl");
              UserService userService = (UserService)clazz.newInstance();
    */
    public static UserService getUserService() {
        UserService userService = null;
        try {
            //直接通过报名获取对象
//             Class clazz = Class.forName("com.chentf.service.impl.UserServiceImpl");
            Class clazz = Class.forName(properties.getProperty("userService"));
            userService = (UserService) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return userService;
    }

    public static UserDAO getUserDAO() {
        UserDAO userDAO = null;
        try {
            Class clazz = Class.forName(properties.getProperty("userDAO"));
            userDAO = (UserDAO) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return userDAO;
    }

    /*
     key 小配置文件中的key [userDAO,userService]
     */
    public static Object getBean(String key) throws ClassNotFoundException {
        Object obj = null;
        Class clazz = Class.forName(properties.getProperty(key));
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
